package com.sy.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sy.dto.JsonResult;
import com.sy.dto.UserSession;
import com.sy.utils.CommonOperations;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

public class SessionFilter implements Filter, CommonOperations {
    private List<String> sessionInteceptorUris;

    @Override
    public void init(FilterConfig filterConfig) {
        //读取记录不需要拦截的路径的那个文件
        try (InputStream is = SessionFilter.class.getClassLoader().getResourceAsStream("session-inteceptor-uris");) {
            sessionInteceptorUris = IOUtils.readLines(is);
            System.out.println(sessionInteceptorUris);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //根据当前的请求路径判断该路径是否在需要验证登录的这些路径中，如果在则进行验证
        String uri = req.getRequestURI();
        System.out.println(uri);
        //1.如果这个路径不需要拦截
        //预览请求不用过滤，直接放行
        if (sessionInteceptorUris.contains(uri) || StringUtils.equals(uri.split("/")[1],"files")) {
            filterChain.doFilter(req, res);
        }
        //2.如果这个路径需要拦截
        else {
            //获取当前登录的用户信息
            UserSession userSession = (UserSession) req.getSession().getAttribute("session");
            //(1)如果没有
            if (Objects.isNull(userSession)) {
                res.setContentType("application/json;charset=utf-8");
                JsonResult jsonResult = new JsonResult();
                int code = HttpStatus.BAD_REQUEST.value();
                res.setStatus(code);
                jsonResult.setCode(code).setError("请先登录！");
                res.getWriter().print(JSON.toJSONString(jsonResult));

            }
            //(2)如果有
            else {
                filterChain.doFilter(req, res);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
